<template>
  <view class="withdraw-apply">


    <!-- 余额显示 -->
    <view class="balance-section">
      <view class="balance-card">
        <text class="balance-label">可提现余额</text>
        <text class="balance-amount">¥{{ balance }}</text>
      </view>
    </view>

    <!-- 提现表单 -->
    <view class="form-section">
      <!-- 提现金额 -->
      <view class="form-item">
        <view class="item-label">提现金额</view>
        <view class="amount-input">
          <text class="currency">¥</text>
          <u-input 
            v-model="form.amount"
            type="number"
            placeholder="请输入提现金额"
            :border="false"
            @input="onAmountChange"
          />
        </view>
        <view class="amount-tips">
          <text class="tip-text">最低{{ config.min_amount || 10 }}元，最高{{ config.max_amount || 10000 }}元</text>
        </view>
      </view>

      <!-- 收款方式 -->
      <view class="form-item">
        <view class="item-label">收款方式</view>
        <view class="payment-methods">
          <view 
            v-for="method in paymentMethods" 
            :key="method.value"
            class="method-item"
            :class="{ active: form.payment_method === method.value }"
            @click="selectPaymentMethod(method.value)"
          >
            <u-icon :name="method.icon" size="24" :color="form.payment_method === method.value ? '#007aff' : '#666'"></u-icon>
            <text class="method-text">{{ method.label }}</text>
          </view>
        </view>
      </view>

      <!-- 收款账户信息 -->
      <view class="form-item" v-if="form.payment_method">
        <view class="item-label">{{ getAccountLabel() }}</view>
        <u-input 
          v-model="form.account"
          :placeholder="getAccountPlaceholder()"
          :border="true"
        />
      </view>

      <!-- 真实姓名 -->
      <view class="form-item" v-if="form.payment_method">
        <view class="item-label">真实姓名</view>
        <u-input 
          v-model="form.real_name"
          placeholder="请输入真实姓名"
          :border="true"
        />
      </view>

      <!-- 手续费信息 -->
      <view class="fee-section" v-if="feeInfo.amount > 0">
        <view class="fee-title">费用明细</view>
        <view class="fee-item">
          <text class="fee-label">提现金额</text>
          <text class="fee-value">¥{{ feeInfo.amount }}</text>
        </view>
        <view class="fee-item">
          <text class="fee-label">手续费</text>
          <text class="fee-value">¥{{ feeInfo.fee }}</text>
        </view>
        <view class="fee-item total">
          <text class="fee-label">实际到账</text>
          <text class="fee-value">¥{{ feeInfo.actual_amount }}</text>
        </view>
      </view>
    </view>

    <!-- 提交按钮 -->
    <view class="submit-section">
      <u-button 
        type="primary" 
        :disabled="!canSubmit"
        @click="handleSubmit"
        :loading="loading"
      >
        确认提现
      </u-button>
    </view>

    <!-- 提现须知 -->
    <view class="notice-section">
      <view class="notice-title">提现须知</view>
      <view class="notice-content">
        <text class="notice-item">1. 请确保收款账户信息准确无误，错误信息可能导致提现失败</text>
        <text class="notice-item">2. 提现申请提交后，资金将被冻结，审核通过后发放</text>
        <text class="notice-item">3. 工作日1-3个工作日到账，节假日顺延</text>
        <text class="notice-item">4. 如有疑问，请联系客服处理</text>
      </view>
    </view>
  </view>
</template>

<script>
import { getConfig, calculateFee, apply } from '@/api/withdraw'
import { getBalance } from '@/api/invite'

export default {
  name: 'WithdrawApply',
  data() {
    return {
      balance: 0,
      config: {},
      form: {
        amount: '',
        payment_method: '',
        account: '',
        real_name: ''
      },
      feeInfo: {
        amount: 0,
        fee: 0,
        actual_amount: 0
      },
      loading: false,
      paymentMethods: [
        { value: 'wechat', label: '微信', icon: 'weixin' },
        { value: 'alipay', label: '支付宝', icon: 'zhifubao' },
        { value: 'bank', label: '银行卡', icon: 'yinhangqia' }
      ]
    }
  },
  computed: {
    canSubmit() {
      return this.form.amount && 
             this.form.payment_method && 
             this.form.account && 
             this.form.real_name &&
             parseFloat(this.form.amount) >= (this.config.min_amount || 10) &&
             parseFloat(this.form.amount) <= this.balance
    }
  },
  onLoad(options) {
    // 如果从其他页面传入金额
    if (options.amount) {
      this.form.amount = options.amount
    }
    this.loadData()
  },
  methods: {
    async loadData() {
      await Promise.all([
        this.loadBalance(),
        this.loadConfig()
      ])
      
      if (this.form.amount) {
        this.calculateWithdrawFee()
      }
    },
    async loadBalance() {
      try {
        const res = await getBalance()
        if (res.code === 0) {
          this.balance = res.data.balance || 0
        }
      } catch (error) {
        console.error('获取余额失败:', error)
      }
    },
    async loadConfig() {
      try {
        const res = await getConfig()
        if (res.code === 0) {
          this.config = res.data || {}
        }
      } catch (error) {
        console.error('获取配置失败:', error)
      }
    },
    onAmountChange() {
      this.calculateWithdrawFee()
    },
    async calculateWithdrawFee() {
      const amount = parseFloat(this.form.amount) || 0
      if (amount <= 0) {
        this.feeInfo = { amount: 0, fee: 0, actual_amount: 0 }
        return
      }
      
      try {
        const res = await calculateFee({ amount })
        if (res.code === 0) {
          this.feeInfo = {
            amount: amount,
            fee: res.data.fee || 0,
            actual_amount: res.data.actual_amount || 0
          }
        }
      } catch (error) {
        console.error('计算手续费失败:', error)
      }
    },
    selectPaymentMethod(method) {
      this.form.payment_method = method
      // 清空账户信息
      this.form.account = ''
      this.form.real_name = ''
    },
    getAccountLabel() {
      const labels = {
        wechat: '微信号',
        alipay: '支付宝账号',
        bank: '银行卡号'
      }
      return labels[this.form.payment_method] || '账号'
    },
    getAccountPlaceholder() {
      const placeholders = {
        wechat: '请输入微信号',
        alipay: '请输入支付宝账号',
        bank: '请输入银行卡号'
      }
      return placeholders[this.form.payment_method] || '请输入账号'
    },
    async handleSubmit() {
      if (!this.canSubmit) {
        uni.showToast({
          title: '请完善提现信息',
          icon: 'none'
        })
        return
      }

      // 二次确认
      const confirmRes = await uni.showModal({
        title: '确认提现',
        content: `确认提现¥${this.form.amount}到${this.getAccountLabel()}？`,
        confirmText: '确认',
        cancelText: '取消'
      })

      if (!confirmRes.confirm) {
        return
      }

      this.loading = true
      try {
        const res = await apply({
          amount: parseFloat(this.form.amount),
          payment_method: this.form.payment_method,
          account: this.form.account,
          real_name: this.form.real_name
        })
        
        if (res.code === 0) {
          uni.showToast({
            title: '提现申请成功',
            icon: 'success'
          })
          
          // 跳转到提现详情页
          setTimeout(() => {
            uni.redirectTo({
              url: `/pages/user/withdraw/detail?id=${res.data.id}`
            })
          }, 1500)
        } else {
          uni.showToast({
            title: res.msg || '提现申请失败',
            icon: 'none'
          })
        }
      } catch (error) {
        console.error('提现申请失败:', error)
        uni.showToast({
          title: '网络错误，请重试',
          icon: 'none'
        })
      } finally {
        this.loading = false
      }
    },

  }
}
</script>

<style lang="scss" scoped>
.withdraw-apply {
  min-height: 100vh;
  background-color: #f8f9fa;
}

.balance-section {
  padding: 20rpx;
  
  .balance-card {
    padding: 40rpx;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    border-radius: 20rpx;
    text-align: center;
    color: white;
    
    .balance-label {
      display: block;
      font-size: 28rpx;
      opacity: 0.9;
      margin-bottom: 10rpx;
    }
    
    .balance-amount {
      display: block;
      font-size: 60rpx;
      font-weight: bold;
    }
  }
}

.form-section {
  margin: 20rpx;
  background: white;
  border-radius: 20rpx;
  overflow: hidden;
  
  .form-item {
    padding: 30rpx;
    border-bottom: 1rpx solid #f0f0f0;
    
    &:last-child {
      border-bottom: none;
    }
    
    .item-label {
      font-size: 32rpx;
      font-weight: bold;
      color: #333;
      margin-bottom: 20rpx;
    }
  }
}

.amount-input {
  display: flex;
  align-items: center;
  padding: 20rpx;
  background: #f8f9fa;
  border-radius: 10rpx;
  
  .currency {
    font-size: 36rpx;
    font-weight: bold;
    color: #333;
    margin-right: 10rpx;
  }
}

.amount-tips {
  margin-top: 15rpx;
  
  .tip-text {
    font-size: 24rpx;
    color: #999;
  }
}

.payment-methods {
  display: flex;
  gap: 20rpx;
  
  .method-item {
    flex: 1;
    padding: 30rpx 20rpx;
    background: #f8f9fa;
    border-radius: 10rpx;
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 10rpx;
    transition: all 0.3s;
    
    &.active {
      background: #e3f2fd;
      border: 2rpx solid #007aff;
    }
    
    .method-text {
      font-size: 24rpx;
      color: #666;
    }
  }
}

.fee-section {
  margin-top: 30rpx;
  padding-top: 30rpx;
  border-top: 1rpx solid #f0f0f0;
  
  .fee-title {
    font-size: 28rpx;
    font-weight: bold;
    color: #333;
    margin-bottom: 20rpx;
  }
  
  .fee-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 10rpx 0;
    
    &.total {
      font-weight: bold;
      color: #007aff;
      border-top: 1rpx solid #f0f0f0;
      padding-top: 20rpx;
      margin-top: 10rpx;
    }
    
    .fee-label {
      font-size: 28rpx;
      color: #666;
    }
    
    .fee-value {
      font-size: 28rpx;
      color: #333;
    }
  }
}

.submit-section {
  margin: 40rpx 20rpx;
}

.notice-section {
  margin: 20rpx;
  padding: 30rpx;
  background: white;
  border-radius: 20rpx;
  
  .notice-title {
    font-size: 32rpx;
    font-weight: bold;
    color: #333;
    margin-bottom: 20rpx;
  }
  
  .notice-content {
    .notice-item {
      display: block;
      font-size: 26rpx;
      color: #666;
      line-height: 1.6;
      margin-bottom: 15rpx;
    }
  }
}
</style>
